import React, { useState } from 'react';
import { Button, Form, Input, message } from 'antd';
import LoginBackground from "@/views/Login/LoginBackground";
import { useNavigate } from "react-router-dom";
import "./register.css"
import registerImage from "/src/assets/register.png"
import baseUrl from '@/config'

const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
};

/* eslint-disable no-template-curly-in-string */
const validateMessages = {
    required: '${label}不得为空！',
    types: {
        email: '${label}格式错误，请修改！',
    },
};

const App: React.FC = () => {
    const navigateTo = useNavigate();
    const [loadings, setLoadings] = useState<boolean[]>([]);
    const [showVerifyCode, setShowVerifyCode] = useState(false);
    const [email, setEmail] = useState('');

    const onFinish = async (values: any) => {
        setLoadings([true]);
        if (showVerifyCode == false) {
            message.warning('请先获取验证码并输入！', 1);
        }
        else {
            try {
                const response = await fetch(baseUrl + '/back/user/register', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(values.userInfo)
                });

                if (response.ok) {
                    // 请求成功
                    const data = await response.json();
                    // 处理响应数据
                    if (data.code === 200) {
                        message.success(data.msg, 2);
                        setShowVerifyCode(false);
                    }
                    else {
                        message.warning(data.msg, 2);
                    }
                } else {
                    // 请求失败
                    console.error('Error:', response.status);
                }
            } catch (error) {
                console.error('Error:', error);
            }
        }
        setLoadings([false]);
    };

    const handleEmailChange = (event: { target: { value: React.SetStateAction<string>; }; }) => {
        setEmail(event.target.value);
    };

    const getVertifyCode = async () => {
        // 在这里添加获取验证码的逻辑
        setLoadings(prevLoadings => {
            // 创建一个新数组，用来存储更新后的状态
            const newLoadings = [...prevLoadings];
            // 更新数组中的第 i 项
            newLoadings[1] = true;
            // 返回新数组，以更新状态
            return newLoadings;
        });
        const emailRegex = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
        if (email === '' || !emailRegex.test(email)) {
            message.warning('请先输入正确格式的邮箱！', 1)
        }
        else {
            try {
                const response = await fetch(baseUrl + '/back/user/getCode', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        email: email,
                        userName: null,
                        account: null,
                        pwd: null,
                        code: null
                    })
                });

                if (response.ok) {
                    // 请求成功
                    const data = await response.json();
                    // 处理响应数据
                    if (data.code === 200) {
                        message.success(data.msg, 2);
                        setShowVerifyCode(true);
                    }
                    else {
                        message.warning(data.msg)
                    }
                } else {
                    // 请求失败
                    console.error('Error:', response.status);
                }
            } catch (error) {
                console.error('Error:', error);
            }
        }
        setLoadings(prevLoadings => {
            // 创建一个新数组，用来存储更新后的状态
            const newLoadings = [...prevLoadings];
            // 更新数组中的第 i 项
            newLoadings[1] = false;
            // 返回新数组，以更新状态
            return newLoadings;
        });
    };

    const goLogin = () => {
        // 在这里添加去登录页面的逻辑
        navigateTo("/login");
    };

    return (
        <>
            <LoginBackground />
            <div className='register-container'>
                <img id="rf-img" src={registerImage} style={{ maxWidth: '100%', height: '100px' }} />
                <Form
                    {...layout}
                    name="nest-messages"
                    onFinish={onFinish}
                    style={{ maxWidth: 600 }}
                    validateMessages={validateMessages}
                >
                    <Form.Item className='register-form' name={['userInfo', 'userName']} label="用户名" rules={[{ required: true }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item
                        className='register-form'
                        label="账号"
                        name={['userInfo', 'account']}
                        rules={[{ required: true, message: '账号不得为空!' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        className='register-form'
                        label="密码"
                        name={['userInfo', 'pwd']}
                        rules={[{ required: true, message: '密码不得为空!' }]}
                    >
                        <Input.Password />
                    </Form.Item>
                    <Form.Item className='register-form' name={['userInfo', 'email']} label="邮箱" rules={[{ type: 'email', required: true }]}>
                        <Input value={email} onChange={handleEmailChange} />
                    </Form.Item>
                    {showVerifyCode && (
                        <Form.Item
                            className='register-form'
                            label="验证码"
                            name={['userInfo', 'code']}
                            rules={[{ required: true, message: '验证码不得为空！' }]}
                        >
                            <Input />
                        </Form.Item>
                    )}
                    <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 8 }}>
                        <Button type="primary" htmlType="submit" className='register-button' loading={loadings[0]}>
                            注册
                        </Button>
                        <Button htmlType="button" onClick={getVertifyCode} className='register-button' loading={loadings[1]}>
                            获取邮箱验证码
                        </Button>
                        <Button htmlType="button" onClick={goLogin} className='go-login-button'>
                            去登陆
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </>
    );
};

export default App;
